package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.entity.QueryCallRecordDataVo;
import com.wtwd.campus.entity.QueryMonitorRecordDataVo;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.service.LogService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.service.UserService;
import com.wtwd.campus.utils.GetCurrentSysUserInfoUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/deviceLog")
public class DeviceLogController {
    private static final Logger logger = LoggerFactory.getLogger(DeviceLogController.class);
    @Autowired
    private LogService logService;
    @Autowired
    private RedisService redisService;
    @Autowired
    public GetCurrentSysUserInfoUtils getCurrentSysUserInfoUtils;
    @Autowired
    public UserService userService;

    /**
     * 查询通话记录
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/getCallRecordList")
    public RespEntity getCallRecordList(@RequestBody QueryCallRecordDataVo data, HttpServletRequest request) {
        logger.info("getCallRecordList: data={}", data.toString());
        //获取用户的组织编号
        String userOrgCode = getUserOrgCode(request);
        if (StringUtils.isBlank(data.getOrgCode())) {
            data.setOrgCode(userOrgCode);
        }
        if (data.getType() == 2) {
            data.setType(null);
        }
        Map<String, Object> callRecord = logService.getCallRecord(data);
        return new RespEntity(RespCode.SUCCESS, callRecord);
    }

    /**
     * 查询监听记录
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/getMonitorRecordList")
    public RespEntity getMonitorRecordList(@RequestBody QueryMonitorRecordDataVo data, HttpServletRequest request) {
        logger.info("getMonitorRecordList: data={}", data.toString());
        //获取用户的组织编号
        String userOrgCode = getUserOrgCode(request);
        if (StringUtils.isBlank(data.getOrgCode())) {
            data.setOrgCode(userOrgCode);
        }
        Map<String, Object> callRecord = logService.getMonitorRecord(data);
        return new RespEntity(RespCode.SUCCESS, callRecord);
    }

    /**
     * 获取用户组织编码
     *
     * @param request
     * @return
     */
    public String getUserOrgCode(HttpServletRequest request) {
        //获取用户的组织编号
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        String userOrgCode = (String) jsonObject.get("orgCode");
        return userOrgCode;
    }


    /**
     * 获取指令下发记录表
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/getCommandRecordList")
    public RespEntity getCommandRecordList(@RequestBody JSONObject jsonObject) {
        logger.info("getCommandRecordList: data={}", jsonObject);
        SysUser userInfo = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (userInfo == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer currentPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");
        //构建查询map
        HashMap<String, Object> searchMap = new HashMap<>();
        String imei = jsonObject.getString("imei");//imei号
        Integer sendType = jsonObject.getInteger("sendType");//发送类型 1-在线 2-离线
        Integer result = jsonObject.getInteger("result");//下发状态(0：待发送，1-发送中，2-完成 3-失败)
        /**
         * 关键字构建（1:白名单,2:课堂模式,3：服务器设置,4.终端操作,5.音量调节,6.工作模式,7.睡眠模式）
         */
        ArrayList<String> commandTypes = new ArrayList<>();
        Integer type = jsonObject.getInteger("commandType");
        if (type != null) {
            switch (type) {
                case 1://白名单
                    commandTypes.add(Constants.SINGLE_WHITELIST_NUMBER);
                    commandTypes.add(Constants.ALL_WHITELIST_NUMBER);
                    commandTypes.add(Constants.UPDATE_WHITE_CALL);
                    commandTypes.add(Constants.DEL_WHITE_CALL);
                    break;
                case 2://课堂模式
                    commandTypes.add(Constants.SET_NO_DISTURB_TIME);
                    commandTypes.add(Constants.DEL_CLASS_MODE);
                    commandTypes.add(Constants.UPDATE_CLASS_MODE);
                    break;
                case 3://服务器设置
                    commandTypes.add(Constants.SET_TEMPORARY_CONTROL_CENTER);
                    commandTypes.add(Constants.SET_DEFAULT_CONTROL_CENTER);
                    break;
                case 4://终端操作
                    commandTypes.add(Constants.SOFTWARE_TURN_OFF);
                    commandTypes.add(Constants.DEVICE_RESTART);
                    commandTypes.add(Constants.FACTORY_RESET);
                    break;
                case 5://音量调节
                    commandTypes.add(Constants.VOLUME_ADJUSTMENT);
                    break;
                case 6://工作模式
                    commandTypes.add(Constants.SET_WORK_MODE);
                    break;
                case 7://睡眠模式
                    commandTypes.add(Constants.AUTO_CHANGE_WORK_MODE);
                    break;
            }
        }
        Long startTime = jsonObject.getLong("startTime");//指令开始时间
        Long endTime = jsonObject.getLong("endTime");//指令结束时间
        searchMap.put("imei", imei);
        searchMap.put("sendType", sendType);
        searchMap.put("result", result);
        searchMap.put("type", type);
        searchMap.put("commandTypes", commandTypes);
        searchMap.put("startTime", startTime);
        searchMap.put("endTime", endTime);
        searchMap.put("currentPage", currentPage);
        searchMap.put("pageSize", pageSize);
        //查询用户的组织code,如果为空，默认为当前用户的组织code
        String orgCode = jsonObject.getString("orgCode");
        if (StringUtils.isBlank(orgCode)) {
            orgCode = userInfo.getOrgCode();
        }
        Page<Object> page = new Page<>(currentPage, pageSize);
        Map<String, Object> restMap = logService.getCommandRecordList(page, searchMap, orgCode);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    /**
     * 告警记录
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/getAlarmRecord")
    public RespEntity getAlarmRecord(@RequestBody JSONObject jsonObject) {
        logger.info("getAlarmRecord: data={}", jsonObject);
        SysUser userInfo = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (userInfo == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer currentPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Page<Object> page = new Page<>(currentPage, pageSize);
        //构建查询map
        HashMap<String, Object> searchMap = new HashMap<>();
        Integer warningType = jsonObject.getInteger("warningType");//警告类型
        String imei = jsonObject.getString("imei");//imei
        String stuName = jsonObject.getString("stuName");//学生姓名
        Long startTime = jsonObject.getLong("startTime");//指令开始时间
        Long endTime = jsonObject.getLong("endTime");//指令结束时间
        searchMap.put("warningType", warningType);
        searchMap.put("imei", imei);
        searchMap.put("stuName", stuName);
        searchMap.put("startTime", startTime);
        searchMap.put("endTime", endTime);
        //查询用户的组织code,如果为空，默认为当前用户的组织code
        String orgCode = jsonObject.getString("orgCode");
        if (StringUtils.isBlank(orgCode)) {
            orgCode = userInfo.getOrgCode();
        }
        Map<String, Object> restMap = logService.getAlarmRecordList(orgCode, searchMap, page);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }


}
